<?php
session_start();
include('../include/dbFunctions.php');

//Setup variables
if(isset($_GET['id'])) {

$deleteID = $_GET['id'];

//$deleteID = $_SESSION['id'];
$ContactTable = "contact_sponsor";
$SchoolTable = "sponsor";
$primary_key = "sponsor_id";


$queryEvent = "SELECT t.event_id
FROM trainer t, volunteer v, sponsor s
WHERE t.volunteer_id = v.volunteer_id
AND v.sponsor_id = s.sponsor_id
AND s.sponsor_id =$deleteID";
$event=executeSelectQuery($queryEvent);
$numevent=count($event);

if($numevent==0){

    //Delete contact from school first
    $query1 = "DELETE FROM $ContactTable WHERE $primary_key = $deleteID";
    $result1 = executeQuery($query1);

    //Delete school secondly
    $query2 = "DELETE FROM $SchoolTable WHERE $primary_key = $deleteID";
    $result2 = executeQuery($query2);
    if ($result2!=0){
        $_SESSION['mes'] = "Your record has been deleted successfully";
    }else{
        $_SESSION['mes'] = "Error! Please try again";
    }
    header('Location: sponsorManage.php');

}else{
    $_SESSION['mes'] = "Cannot delete this sponsor because there is related event.";
    header('Location: sponsorManage.php');
}


}

if(isset($_POST['id_sponsor'])) {
   $id_sponsor=$_POST['id_sponsor'];



    for ($i=0;$i<count($id_sponsor);$i++) {
         $queryEvent = "SELECT t.event_id
FROM trainer t, volunteer v, sponsor s
WHERE t.volunteer_id = v.volunteer_id
AND v.sponsor_id = s.sponsor_id
AND s.sponsor_id =$id_sponsor[$i]";
$event=executeSelectQuery($queryEvent);
$numevent=count($event);

if($numevent==0){

            $uQuery= "DELETE FROM sponsor
        WHERE sponsor_id='".$id_sponsor[$i]."'";
            $uResult = executeQuery($uQuery);

        if ($uResult!=0) {
            $_SESSION['mes'] = "Your record has been deleted successfully";
        }else {
            $_SESSION['mes'] = "Error! Please try again";
        }
        header('Location: sponsorManage.php');
}else{
    $_SESSION['mes'] = "Cannot delete this sponsor because there is related event.";
    header('Location: sponsorManage.php');

    }

        
}


        
    }

?>
